# 监控与统计智能体

from typing import Dict, Any, Optional, List
from datetime import datetime, timedelta
import asyncio
import json
from dataclasses import dataclass, asdict
from enum import Enum
import logging
from collections import defaultdict, deque
import threading
import time
import psutil
import os

from utils.logger import Logger
from utils.exceptions import MonitorError
from states.database_manager import DatabaseManager
from states.langsmith_monitor import LangSmithMonitor

logger = get_logger("monitor_agent")


class MetricType(Enum):
    """指标类型"""
    COUNTER = "counter"        # 计数器
    GAUGE = "gauge"            # 仪表盘
    HISTOGRAM = "histogram"    # 直方图
    SUMMARY = "summary"        # 摘要


class AlertLevel(Enum):
    """告警级别"""
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"
    CRITICAL = "critical"


@dataclass
class MetricData:
    """指标数据"""
    name: str
    metric_type: MetricType
    value: float
    labels: Dict[str, str]
    timestamp: datetime
    description: Optional[str] = None


@dataclass
class AlertData:
    """告警数据"""
    alert_id: str
    level: AlertLevel
    title: str
    message: str
    metric_name: str
    threshold: float
    current_value: float
    timestamp: datetime
    resolved: bool = False
    resolved_at: Optional[datetime] = None


class MetricsCollector:
    """指标收集器"""

    def __init__(self, max_history: int = 10000):
        self.max_history = max_history
        self.metrics_history: Dict[str, deque] = defaultdict(lambda: deque(maxlen=max_history))
        self.current_metrics: Dict[str, MetricData] = {}
        self._lock = threading.Lock()

    def record_metric(self, metric_data: MetricData):
        """记录指标"""
        with self._lock:
            # 生成指标键
            metric_key = f"{metric_data.name}:{json.dumps(metric_data.labels, sort_keys=True)}"
            
            # 记录历史数据
            self.metrics_history[metric_key].append(metric_data)
            
            # 更新当前指标
            self.current_metrics[metric_key] = metric_data
            
            logger.debug(f"指标记录完成: {metric_data.name}={metric_data.value}")

    def get_metric(self, name: str, labels: Optional[Dict[str, str]] = None) -> Optional[MetricData]:
        """获取指标"""
        with self._lock:
            if labels:
                metric_key = f"{name}:{json.dumps(labels, sort_keys=True)}"
            else:
                # 查找第一个匹配的指标
                for key, metric in self.current_metrics.items():
                    if key.startswith(f"{name}:"):
                        return metric
                return None
            
            return self.current_metrics.get(metric_key)

    def get_metric_history(self, name: str, labels: Optional[Dict[str, str]] = None,
                           time_range: Optional[timedelta] = None) -> List[MetricData]:
        """获取指标历史"""
        with self._lock:
            if labels:
                metric_key = f"{name}:{json.dumps(labels, sort_keys=True)}"
            else:
                # 查找所有匹配的指标
                matching_metrics = []
                for key, history in self.metrics_history.items():
                    if key.startswith(f"{name}:"):
                        matching_metrics.extend(list(history))
                
                # 按时间过滤
                if time_range:
                    cutoff_time = datetime.now() - time_range
                    matching_metrics = [m for m in matching_metrics if m.timestamp >= cutoff_time]
                
                return sorted(matching_metrics, key=lambda x: x.timestamp)
            
            history = list(self.metrics_history.get(metric_key, []))
            
            # 按时间过滤
            if time_range:
                cutoff_time = datetime.now() - time_range
                history = [m for m in history if m.timestamp >= cutoff_time]
            
            return history

    def get_all_metrics(self) -> List[MetricData]:
        """获取所有当前指标"""
        with self._lock:
            return list(self.current_metrics.values())

    def get_metric_summary(self, name: str, labels: Optional[Dict[str, str]] = None,
                           time_range: Optional[timedelta] = None) -> Dict[str, Any]:
        """获取指标摘要"""
        history = self.get_metric_history(name, labels, time_range)
        
        if not history:
            return {}
        
        values = [m.value for m in history]
        
        return {
            "name": name,
            "count": len(values),
            "min": min(values),
            "max": max(values),
            "avg": sum(values) / len(values),
            "latest": values[-1],
            "timestamp_range": {
                "start": history[0].timestamp.isoformat(),
                "end": history[-1].timestamp.isoformat()
            }
        }


class SystemMetricsCollector:
    """系统指标收集器"""

    def __init__(self):
        self.process = psutil.Process(os.getpid())

    def collect_cpu_metrics(self) -> List[MetricData]:
        """收集CPU指标"""
        metrics = []
        
        # CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        metrics.append(MetricData(
            name="system_cpu_usage_percent",
            metric_type=MetricType.GAUGE,
            value=cpu_percent,
            labels={"type": "total"},
            timestamp=datetime.now(),
            description="系统CPU使用率百分比"
        ))
        
        # 每个CPU核心的使用率
        cpu_per_cpu = psutil.cpu_percent(interval=1, percpu=True)
        for i, cpu_percent in enumerate(cpu_per_cpu):
            metrics.append(MetricData(
                name="system_cpu_usage_percent",
                metric_type=MetricType.GAUGE,
                value=cpu_percent,
                labels={"type": "per_cpu", "cpu_id": str(i)},
                timestamp=datetime.now(),
                description=f"CPU核心 {i} 使用率百分比"
            ))
        
        return metrics

    def collect_memory_metrics(self) -> List[MetricData]:
        """收集内存指标"""
        metrics = []
        
        # 系统内存
        memory = psutil.virtual_memory()
        metrics.append(MetricData(
            name="system_memory_usage_percent",
            metric_type=MetricType.GAUGE,
            value=memory.percent,
            labels={"type": "total"},
            timestamp=datetime.now(),
            description="系统内存使用率百分比"
        ))
        
        metrics.append(MetricData(
            name="system_memory_available_bytes",
            metric_type=MetricType.GAUGE,
            value=memory.available,
            labels={"type": "available"},
            timestamp=datetime.now(),
            description="系统可用内存字节数"
        ))
        
        metrics.append(MetricData(
            name="system_memory_used_bytes",
            metric_type=MetricType.GAUGE,
            value=memory.used,
            labels={"type": "used"},
            timestamp=datetime.now(),
            description="系统已用内存字节数"
        ))
        
        # 进程内存
        process_memory = self.process.memory_info()
        metrics.append(MetricData(
            name="process_memory_rss_bytes",
            metric_type=MetricType.GAUGE,
            value=process_memory.rss,
            labels={"type": "rss"},
            timestamp=datetime.now(),
            description="进程RSS内存字节数"
        ))
        
        metrics.append(MetricData(
            name="process_memory_vms_bytes",
            metric_type=MetricType.GAUGE,
            value=process_memory.vms,
            labels={"type": "vms"},
            timestamp=datetime.now(),
            description="进程VMS内存字节数"
        ))
        
        return metrics

    def collect_disk_metrics(self) -> List[MetricData]:
        """收集磁盘指标"""
        metrics = []
        
        # 磁盘使用率
        disk_usage = psutil.disk_usage('/')
        metrics.append(MetricData(
            name="disk_usage_percent",
            metric_type=MetricType.GAUGE,
            value=disk_usage.percent,
            labels={"path": "/", "type": "usage"},
            timestamp=datetime.now(),
            description="根磁盘使用率百分比"
        ))
        
        metrics.append(MetricData(
            name="disk_free_bytes",
            metric_type=MetricType.GAUGE,
            value=disk_usage.free,
            labels={"path": "/", "type": "free"},
            timestamp=datetime.now(),
            description="根磁盘可用空间字节数"
        ))
        
        metrics.append(MetricData(
            name="disk_used_bytes",
            metric_type=MetricType.GAUGE,
            value=disk_usage.used,
            labels={"path": "/", "type": "used"},
            timestamp=datetime.now(),
            description="根磁盘已用空间字节数"
        ))
        
        # 磁盘I/O
        disk_io = psutil.disk_io_counters()
        if disk_io:
            metrics.append(MetricData(
                name="disk_read_bytes_total",
                metric_type=MetricType.COUNTER,
                value=disk_io.read_bytes,
                labels={"type": "read"},
                timestamp=datetime.now(),
                description="磁盘读取总字节数"
            ))
            
            metrics.append(MetricData(
                name="disk_write_bytes_total",
                metric_type=MetricType.COUNTER,
                value=disk_io.write_bytes,
                labels={"type": "write"},
                timestamp=datetime.now(),
                description="磁盘写入总字节数"
            ))
        
        return metrics

    def collect_network_metrics(self) -> List[MetricData]:
        """收集网络指标"""
        metrics = []
        
        # 网络I/O
        net_io = psutil.net_io_counters()
        if net_io:
            metrics.append(MetricData(
                name="network_bytes_sent_total",
                metric_type=MetricType.COUNTER,
                value=net_io.bytes_sent,
                labels={"type": "sent"},
                timestamp=datetime.now(),
                description="网络发送总字节数"
            ))
            
            metrics.append(MetricData(
                name="network_bytes_recv_total",
                metric_type=MetricType.COUNTER,
                value=net_io.bytes_recv,
                labels={"type": "recv"},
                timestamp=datetime.now(),
                description="网络接收总字节数"
            ))
            
            metrics.append(MetricData(
                name="network_packets_sent_total",
                metric_type=MetricType.COUNTER,
                value=net_io.packets_sent,
                labels={"type": "packets_sent"},
                timestamp=datetime.now(),
                description="网络发送总包数"
            ))
            
            metrics.append(MetricData(
                name="network_packets_recv_total",
                metric_type=MetricType.COUNTER,
                value=net_io.packets_recv,
                labels={"type": "packets_recv"},
                timestamp=datetime.now(),
                description="网络接收总包数"
            ))
        
        return metrics

    def collect_all_system_metrics(self) -> List[MetricData]:
        """收集所有系统指标"""
        metrics = []
        
        try:
            metrics.extend(self.collect_cpu_metrics())
            metrics.extend(self.collect_memory_metrics())
            metrics.extend(self.collect_disk_metrics())
            metrics.extend(self.collect_network_metrics())
        except Exception as e:
            logger.error(f"收集系统指标失败: {str(e)}")
        
        return metrics


class ApplicationMetricsCollector:
    """应用指标收集器"""

    def __init__(self, db_manager: DatabaseManager, langsmith_monitor: LangSmithMonitor):
        self.db_manager = db_manager
        self.langsmith_monitor = langsmith_monitor

    async def collect_task_metrics(self) -> List[MetricData]:
        """收集任务指标"""
        metrics = []
        
        try:
            # 获取任务统计
            task_stats = await self.db_manager.get_task_statistics()
            
            for status, count in task_stats.items():
                metrics.append(MetricData(
                    name="maess_task_count",
                    metric_type=MetricType.GAUGE,
                    value=count,
                    labels={"status": status},
                    timestamp=datetime.now(),
                    description=f"任务状态为 {status} 的数量"
                ))
            
            # 获取任务队列统计
            queue_stats = await self.db_manager.get_queue_statistics()
            for queue_name, stats in queue_stats.items():
                metrics.append(MetricData(
                    name="maess_queue_size",
                    metric_type=MetricType.GAUGE,
                    value=stats.get("size", 0),
                    labels={"queue": queue_name},
                    timestamp=datetime.now(),
                    description=f"队列 {queue_name} 的大小"
                ))
        
        except Exception as e:
            logger.error(f"收集任务指标失败: {str(e)}")
        
        return metrics

    async def collect_agent_metrics(self) -> List[MetricData]:
        """收集智能体指标"""
        metrics = []
        
        try:
            # 获取智能体统计
            agent_stats = await self.db_manager.get_agent_statistics()
            
            for agent_type, stats in agent_stats.items():
                # 智能体执行次数
                metrics.append(MetricData(
                    name="maess_agent_execution_count",
                    metric_type=MetricType.COUNTER,
                    value=stats.get("execution_count", 0),
                    labels={"agent_type": agent_type},
                    timestamp=datetime.now(),
                    description=f"智能体 {agent_type} 的执行次数"
                ))
                
                # 智能体平均执行时间
                avg_execution_time = stats.get("avg_execution_time", 0)
                if avg_execution_time > 0:
                    metrics.append(MetricData(
                        name="maess_agent_execution_duration_seconds",
                        metric_type=MetricType.GAUGE,
                        value=avg_execution_time,
                        labels={"agent_type": agent_type},
                        timestamp=datetime.now(),
                        description=f"智能体 {agent_type} 的平均执行时间（秒）"
                    ))
                
                # 智能体成功率
                success_rate = stats.get("success_rate", 0)
                metrics.append(MetricData(
                    name="maess_agent_success_rate",
                    metric_type=MetricType.GAUGE,
                    value=success_rate,
                    labels={"agent_type": agent_type},
                    timestamp=datetime.now(),
                    description=f"智能体 {agent_type} 的成功率"
                ))
        
        except Exception as e:
            logger.error(f"收集智能体指标失败: {str(e)}")
        
        return metrics

    async def collect_all_application_metrics(self) -> List[MetricData]:
        """收集所有应用指标"""
        metrics = []
        
        try:
            task_metrics = await self.collect_task_metrics()
            metrics.extend(task_metrics)
            
            agent_metrics = await self.collect_agent_metrics()
            metrics.extend(agent_metrics)
        except Exception as e:
            logger.error(f"收集应用指标失败: {str(e)}")
        
        return metrics


class AlertManager:
    """告警管理器"""

    def __init__(self):
        self.active_alerts: Dict[str, AlertData] = {}
        self.alert_rules: List[Dict[str, Any]] = []
        self._lock = threading.Lock()

    def add_alert_rule(self, rule: Dict[str, Any]):
        """添加告警规则"""
        self.alert_rules.append(rule)
        logger.info(f"告警规则添加完成: {rule.get('name', 'unknown')}")

    def check_alerts(self, metrics: List[MetricData]) -> List[AlertData]:
        """检查告警"""
        new_alerts = []
        
        with self._lock:
            for rule in self.alert_rules:
                try:
                    alerts = self._evaluate_rule(rule, metrics)
                    new_alerts.extend(alerts)
                except Exception as e:
                    logger.error(f"评估告警规则失败: {str(e)}")
        
        return new_alerts

    def _evaluate_rule(self, rule: Dict[str, Any], metrics: List[MetricData]) -> List[AlertData]:
        """评估告警规则"""
        alerts = []
        rule_name = rule.get('name', 'unknown')
        
        for metric in metrics:
            # 检查规则是否适用于此指标
            if not self._rule_applies_to_metric(rule, metric):
                continue
            
            # 评估阈值条件
            if self._evaluate_threshold(rule, metric):
                # 创建告警
                alert_id = f"{rule_name}:{metric.name}:{json.dumps(metric.labels, sort_keys=True)}"
                
                if alert_id not in self.active_alerts:
                    alert = AlertData(
                        alert_id=alert_id,
                        level=AlertLevel(rule.get('level', 'warning')),
                        title=rule.get('title', f"告警: {metric.name}"),
                        message=rule.get('message', f"指标 {metric.name} 超过阈值"),
                        metric_name=metric.name,
                        threshold=rule.get('threshold', 0),
                        current_value=metric.value,
                        timestamp=datetime.now()
                    )
                    
                    self.active_alerts[alert_id] = alert
                    alerts.append(alert)
                    
                    logger.warning(f"新告警触发: {alert.title}, 当前值={metric.value}, 阈值={rule.get('threshold', 0)}")
            else:
                # 检查是否需要解除告警
                alert_id = f"{rule_name}:{metric.name}:{json.dumps(metric.labels, sort_keys=True)}"
                if alert_id in self.active_alerts:
                    alert = self.active_alerts[alert_id]
                    alert.resolved = True
                    alert.resolved_at = datetime.now()
                    
                    del self.active_alerts[alert_id]
                    
                    logger.info(f"告警已解除: {alert.title}")
        
        return alerts

    def _rule_applies_to_metric(self, rule: Dict[str, Any], metric: MetricData) -> bool:
        """检查规则是否适用于指标"""
        # 检查指标名称
        if 'metric_name' in rule and rule['metric_name'] != metric.name:
            return False
        
        # 检查标签
        if 'labels' in rule:
            for key, value in rule['labels'].items():
                if key not in metric.labels or metric.labels[key] != value:
                    return False
        
        return True

    def _evaluate_threshold(self, rule: Dict[str, Any], metric: MetricData) -> bool:
        """评估阈值条件"""
        operator = rule.get('operator', '>')
        threshold = rule.get('threshold', 0)
        
        if operator == '>':
            return metric.value > threshold
        elif operator == '>=':
            return metric.value >= threshold
        elif operator == '<':
            return metric.value < threshold
        elif operator == '<=':
            return metric.value <= threshold
        elif operator == '==':
            return metric.value == threshold
        elif operator == '!=':
            return metric.value != threshold
        else:
            logger.warning(f"未知的操作符: {operator}")
            return False

    def get_active_alerts(self) -> List[AlertData]:
        """获取活跃告警"""
        with self._lock:
            return list(self.active_alerts.values())

    def get_alert_summary(self) -> Dict[str, Any]:
        """获取告警摘要"""
        with self._lock:
            active_alerts = list(self.active_alerts.values())
            
            summary = {
                "total_alerts": len(active_alerts),
                "by_level": defaultdict(int),
                "by_metric": defaultdict(int),
                "latest_alerts": sorted(active_alerts, key=lambda x: x.timestamp, reverse=True)[:10]
            }
            
            for alert in active_alerts:
                summary["by_level"][alert.level.value] += 1
                summary["by_metric"][alert.metric_name] += 1
            
            return summary


class MonitorAgent:
    """监控与统计智能体"""

    def __init__(self, db_manager: DatabaseManager, langsmith_monitor: LangSmithMonitor):
        self.db_manager = db_manager
        self.langsmith_monitor = langsmith_monitor
        
        self.metrics_collector = MetricsCollector()
        self.system_collector = SystemMetricsCollector()
        self.app_collector = ApplicationMetricsCollector(db_manager, langsmith_monitor)
        self.alert_manager = AlertManager()
        
        self.is_running = False
        self.monitor_task = None
        self.collect_interval = 30  # 秒
        
        self._setup_default_alert_rules()

    def _setup_default_alert_rules(self):
        """设置默认告警规则"""
        default_rules = [
            {
                "name": "high_cpu_usage",
                "metric_name": "system_cpu_usage_percent",
                "operator": ">",
                "threshold": 80,
                "level": "warning",
                "title": "CPU使用率过高",
                "message": "系统CPU使用率超过80%，当前值为{current_value}%"
            },
            {
                "name": "high_memory_usage",
                "metric_name": "system_memory_usage_percent",
                "operator": ">",
                "threshold": 85,
                "level": "warning",
                "title": "内存使用率过高",
                "message": "系统内存使用率超过85%，当前值为{current_value}%"
            },
            {
                "name": "low_disk_space",
                "metric_name": "disk_usage_percent",
                "operator": ">",
                "threshold": 90,
                "level": "error",
                "title": "磁盘空间不足",
                "message": "磁盘使用率超过90%，当前值为{current_value}%"
            },
            {
                "name": "high_task_failure_rate",
                "metric_name": "maess_task_success_rate",
                "labels": {"status": "failed"},
                "operator": "<",
                "threshold": 0.9,
                "level": "error",
                "title": "任务失败率过高",
                "message": "任务失败率超过10%，当前失败率为{current_value}%"
            },
            {
                "name": "high_agent_failure_rate",
                "metric_name": "maess_agent_success_rate",
                "operator": "<",
                "threshold": 0.8,
                "level": "error",
                "title": "智能体失败率过高",
                "message": "智能体成功率低于80%，当前成功率为{current_value}%"
            }
        ]
        
        for rule in default_rules:
            self.alert_manager.add_alert_rule(rule)

    async def start_monitoring(self):
        """开始监控"""
        if self.is_running:
            return
        
        self.is_running = True
        self.monitor_task = asyncio.create_task(self._monitor_loop())
        
        logger.info("监控智能体已启动")

    async def stop_monitoring(self):
        """停止监控"""
        if not self.is_running:
            return
        
        self.is_running = False
        
        if self.monitor_task:
            self.monitor_task.cancel()
            try:
                await self.monitor_task
            except asyncio.CancelledError:
                pass
        
        logger.info("监控智能体已停止")

    async def _monitor_loop(self):
        """监控循环"""
        while self.is_running:
            try:
                await self._collect_and_process_metrics()
                await asyncio.sleep(self.collect_interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"监控循环异常: {str(e)}")
                await asyncio.sleep(self.collect_interval)

    async def _collect_and_process_metrics(self):
        """收集和处理指标"""
        try:
            all_metrics = []
            
            # 收集系统指标
            system_metrics = self.system_collector.collect_all_system_metrics()
            all_metrics.extend(system_metrics)
            
            # 收集应用指标
            app_metrics = await self.app_collector.collect_all_application_metrics()
            all_metrics.extend(app_metrics)
            
            # 记录所有指标
            for metric in all_metrics:
                self.metrics_collector.record_metric(metric)
            
            # 检查告警
            alerts = self.alert_manager.check_alerts(all_metrics)
            
            # 存储告警到数据库
            for alert in alerts:
                await self._store_alert(alert)
            
            # 存储指标到数据库
            await self._store_metrics(all_metrics)
            
            logger.info(f"指标收集和处理完成: 指标数量={len(all_metrics)}, 新告警数量={len(alerts)}")
            
        except Exception as e:
            logger.error(f"收集和处理指标失败: {str(e)}")

    async def _store_metrics(self, metrics: List[MetricData]):
        """存储指标到数据库"""
        try:
            # 批量存储指标
            metrics_data = [asdict(metric) for metric in metrics]
            await self.db_manager.bulk_insert_metrics(metrics_data)
            
        except Exception as e:
            logger.error(f"存储指标失败: {str(e)}")

    async def _store_alert(self, alert: AlertData):
        """存储告警到数据库"""
        try:
            alert_data = asdict(alert)
            await self.db_manager.insert_alert(alert_data)
            
        except Exception as e:
            logger.error(f"存储告警失败: {str(e)}")

    def get_current_metrics(self) -> List[MetricData]:
        """获取当前指标"""
        return self.metrics_collector.get_all_metrics()

    def get_metric_history(self, name: str, labels: Optional[Dict[str, str]] = None,
                          time_range: Optional[timedelta] = None) -> List[MetricData]:
        """获取指标历史"""
        return self.metrics_collector.get_metric_history(name, labels, time_range)

    def get_metric_summary(self, name: str, labels: Optional[Dict[str, str]] = None,
                          time_range: Optional[timedelta] = None) -> Dict[str, Any]:
        """获取指标摘要"""
        return self.metrics_collector.get_metric_summary(name, labels, time_range)

    def get_active_alerts(self) -> List[AlertData]:
        """获取活跃告警"""
        return self.alert_manager.get_active_alerts()

    def get_alert_summary(self) -> Dict[str, Any]:
        """获取告警摘要"""
        return self.alert_manager.get_alert_summary()

    async def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        try:
            current_metrics = self.get_current_metrics()
            active_alerts = self.get_active_alerts()
            alert_summary = self.get_alert_summary()
            
            # 计算系统健康度
            system_health = self._calculate_system_health(current_metrics, active_alerts)
            
            return {
                "status": "healthy" if system_health > 0.8 else "degraded" if system_health > 0.5 else "unhealthy",
                "health_score": system_health,
                "metrics_count": len(current_metrics),
                "active_alerts_count": len(active_alerts),
                "alert_summary": alert_summary,
                "timestamp": datetime.now().isoformat()
            }
            
        except Exception as e:
            logger.error(f"获取系统状态失败: {str(e)}")
            return {
                "status": "error",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }

    def _calculate_system_health(self, metrics: List[MetricData], alerts: List[AlertData]) -> float:
        """计算系统健康度"""
        try:
            health_score = 1.0
            
            # 基于告警调整健康度
            for alert in alerts:
                if alert.level == AlertLevel.WARNING:
                    health_score -= 0.1
                elif alert.level == AlertLevel.ERROR:
                    health_score -= 0.2
                elif alert.level == AlertLevel.CRITICAL:
                    health_score -= 0.3
            
            # 基于关键指标调整健康度
            for metric in metrics:
                if metric.name == "system_cpu_usage_percent" and metric.value > 90:
                    health_score -= 0.1
                elif metric.name == "system_memory_usage_percent" and metric.value > 95:
                    health_score -= 0.1
                elif metric.name == "disk_usage_percent" and metric.value > 95:
                    health_score -= 0.2
            
            return max(0.0, min(1.0, health_score))
            
        except Exception as e:
            logger.error(f"计算系统健康度失败: {str(e)}")
            return 0.5  # 默认中等健康度

    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            # 检查数据库连接
            db_healthy = await self.db_manager.health_check()
            
            # 检查LangSmith连接
            langsmith_healthy = await self.langsmith_monitor.health_check()
            
            # 检查监控功能
            monitoring_healthy = self.is_running
            
            return {
                "status": "healthy" if all([db_healthy.get("status") == "healthy", 
                                            langsmith_healthy.get("status") == "healthy", 
                                            monitoring_healthy]) else "unhealthy",
                "database": db_healthy,
                "langsmith": langsmith_healthy,
                "monitoring": {"status": "running" if monitoring_healthy else "stopped"},
                "timestamp": datetime.now().isoformat()
            }
            
        except Exception as e:
            logger.error(f"健康检查失败: {str(e)}")
            return {
                "status": "error",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }


# 全局监控智能体实例
monitor_agent = None


async def get_monitor_agent() -> MonitorAgent:
    """获取监控智能体实例"""
    global monitor_agent
    if monitor_agent is None:
        from states.database_manager import get_database_manager
        from states.langsmith_monitor import get_langsmith_monitor
        
        db_manager = await get_database_manager()
        langsmith_monitor = await get_langsmith_monitor()
        
        monitor_agent = MonitorAgent(db_manager, langsmith_monitor)
    
    return monitor_agent